package com.loong.tool.code;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

/**
 * 二维码图片生成器
 *
 * @author 张成轩
 */
public class BCode {

	/** 默认编码 */
	private static String CHARTSET = "UTF-8";
	/** 默认宽度 */
	private static int DEFAULT_WIDTH = 200;
	/** 默认高度 */
	private static int DEFAULT_HEIGHT = 200;

	/**
	 * 获取二维码
	 * 
	 * @param content 内容
	 * @return 二维码图片对象
	 */
	public static BufferedImage getBc(String content) {

		return getBc(content, DEFAULT_WIDTH, DEFAULT_HEIGHT);
	}

	/**
	 * 获取二维码
	 * 
	 * @param content 内容
	 * @param width 宽
	 * @param height 高
	 * @return 二维码图片对象
	 */
	public static BufferedImage getBc(String content, int width, int height) {

		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, CHARTSET);

		BitMatrix bm;
		try {
			bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		} catch (WriterException e) {
			throw new RuntimeException(e);
		}
		return MatrixToImageWriter.toBufferedImage(bm);
	}

	/**
	 * 读取二维码
	 * 
	 * @param image 二维码图片对象
	 * @return 内容
	 */
	public static String readBc(BufferedImage image) {

		Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

		LuminanceSource source = new BufferedImageLuminanceSource(image);
		Binarizer binarizer = new HybridBinarizer(source);
		BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
		Result content;
		try {
			content = new MultiFormatReader().decode(binaryBitmap, hints);
		} catch (NotFoundException e) {
			throw new RuntimeException(e);
		}
		return content.toString();
	}
}
